# encoding=utf-8

import os
import glob

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

# 可以解析自定义user信息
class Config:
    def __init__(self, config_path="config", config_file=None):
        self.config_path = config_path
        self.config_file = config_file

        if not config_file:
            config_files = glob.glob(os.path.join(self.config_path, 'config*.xml'))
            config_files = [file for file in config_files if file.endswith(".xml")]
            assert len(config_files) > 0, '{}目录中不存在配置文件'.format(self.config_path)
            self.config_file = config_files[0] # 取第一个配置文件， TODO： 多个文件怎么处理？

    def get_user_uid_list(self):
        return [self.getXml('UserA/UID'), self.getXml('UserB/UID'), self.getXml('UserC/UID'), self.getXml('UserD/UID'),
                self.getXml('UserE/UID'), self.getXml('UserF/UID'), self.getXml('UserG/UID'), self.getXml('UserH/UID'),
                self.getXml('UserI/UID'), self.getXml('UserJ/UID')]

    def get_user_account_list(self):
        return [self.getXml('UserA/account'), self.getXml('UserB/account'), self.getXml('UserC/account'), self.getXml('UserD/account'),
                self.getXml('UserE/account'), self.getXml('UserF/account'), self.getXml('UserG/account'), self.getXml('UserH/account'),
                self.getXml('UserI/account'), self.getXml('UserJ/account')]

    def get_user_password_list(self):
        return [self.getXml('UserA/userPassword'), self.getXml('UserB/userPassword'), self.getXml('UserC/userPassword'),
                self.getXml('UserD/userPassword'),
                self.getXml('UserE/userPassword'), self.getXml('UserF/userPassword'), self.getXml('UserG/userPassword'),
                self.getXml('UserH/userPassword'),
                self.getXml('UserI/userPassword'), self.getXml('UserJ/userPassword')]

    def get_userA_uid(self):
        return self.getXml('UserA/UID')

    def get_userB_uid(self):
        return self.getXml('UserB/UID')

    def get_userC_uid(self):
        return self.getXml('UserC/UID')

    def get_userD_uid(self):
        return self.getXml('UserD/UID')

    def get_channelid1(self):
        return self.getXml('Channel_1/channel_ID')

    def get_channelid2(self):
        return self.getXml('Channel_2/channel_ID')

    def get_channelid3(self):
        return self.getXml('Channel_3/channel_ID')

    def getPort(self):
        return int(self.getXml('Common/localHttpServerPort'))

    def getAppId(self):
        return (self.getXml('Common/appId'))

    def getXml(self, node):
        return self._get_xml_node_value(node)

    def _get_xml_node_value(self, node):
        tree = ET.ElementTree(file=os.path.join(self.config_path, self.config_file))
        element = None
        for elem in tree.iterfind(node):
            element = elem
            break
        assert element is not None, "配置项{}不存在".format(node)
        return element.text